package com.huoyun.cargo.action;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.huoyun.base.action.BaseAction;
import com.huoyun.base.bean.Page;
import com.huoyun.car.model.BidCarInfoModel;
import com.huoyun.car.service.CarPubInfoService;
import com.huoyun.cargo.bean.CargoInfo;
import com.huoyun.cargo.bean.CargoItem;
import com.huoyun.cargo.service.CargoService;
import com.huoyun.cargo.service.evt.GetCargosByUserIdEvt;
import com.huoyun.cargo.service.evt.GetSimilarCargoByRouteEvt;
import com.huoyun.common.service.BidInfoService;
import com.huoyun.invoice.bean.Invoice;
import com.huoyun.invoice.service.InvoiceService;
import com.huoyun.userAdmin.bean.Address;
import com.huoyun.userAdmin.service.AddressService;

public class CargoAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3053748604818283321L;

	private CargoService cargoService ;
	
	private AddressService addressService;
	
	private InvoiceService invoiceService;
	
	private BidInfoService bidInfoService;
	
	private CarPubInfoService carPubInfoService;

	private CargoInfo cargo;
	
	private List<CargoInfo> cargoList;
	
	private List<Address> addressList;
	
	private List<BidCarInfoModel> contactCarList;
	
	private Page similarCargoPage;
	
	private Page cargoPage;
	
	private long cargoId;
	
	private CargoItem cargoItem;
	
	private Invoice invoice;
	
	private String hasInvoice;
	
	public String demo(){
		
		return SUCCESS;
	}
	
	public String viewCargo()
	{
		try
		{
			cargo = cargoService.getCargoInfoById(cargoId);
			contactCarList=carPubInfoService.queryBidCars(cargoId, null);
			GetSimilarCargoByRouteEvt similarEvt=new GetSimilarCargoByRouteEvt();
			similarEvt.setGoodsId(cargoId);
			similarEvt.setStartProvince(cargo.getStartProvince());
			similarEvt.setStartCity(cargo.getStartCity());
			similarEvt.setDestinationProvince(cargo.getDestinationProvince());
			similarEvt.setDestinationCity(cargo.getDestinationCity());
			similarEvt.setPageCount(PAGE_COUNT);
			similarEvt.setPageNo(pageNo);
			similarCargoPage=cargoService.getSimilarCargoByRoute(similarEvt);
			cargoService.updateViewCount(cargo.getViewCount()+1, cargo.getId());
		}
		catch (Exception e) {
			return ERROR;
		}
		return SUCCESS;
	}
	
	public String preAddCargo()
	{
		return SUCCESS;
	}
	
	public String addCargo()
	{
		try
		{
			//当前的登录的用户id
			long userId=this.getLoginUser().getId();
			
			cargo.setUserId(userId);
			cargo.setStatus(0);
			
			// 计算费率
			String rate = null;
			if(StringUtils.isNotEmpty(cargo.getFreight()))
			{
			      BigDecimal amount = new BigDecimal(cargo.getAmount());
			      BigDecimal freight = new BigDecimal(cargo.getFreight());
			      rate = freight.divide(amount,2,BigDecimal.ROUND_DOWN).toString();
			}
			cargo.setRate(rate);
			
			//将用户添加的货物信息先放到session中，在用户点击到下一步
			getSession().setAttribute("cargoInfo", cargo);
			//cargoService.saveCargoInfo(cargo);
			
			//获取用户的所有邮寄地址
			addressList= addressService.getAddressByUserId(userId);
		}
		catch (Exception e) {
			// TODO: handle exception
			e.fillInStackTrace();
		}
		return SUCCESS;
	}
	
	public String saveInvoice(){
		
		try {
			
			cargo = (CargoInfo)getSession().getAttribute("cargoInfo");
			//如果session中存在用户添加的货物信息，将其保存
			if(cargo != null)
			{
				if(hasInvoice.equalsIgnoreCase("yes"))
				{
					if(StringUtils.isEmpty(invoice.getTitle()))
					{
						this.setResultMsg("请输入发票抬头");
						return INPUT;
					}
					
					Address address = addressService.getAddressById(invoice.getAddressId());
					
					if(address == null)
					{
						this.setResultMsg("请选择邮寄地址");
						return INPUT;
					}
					
					//保存发票信息
					invoiceService.saveInvoice(invoice);
					
					cargo.setInvoiceId(invoice.getId());
				}
				
				cargoService.saveCargoInfo(cargo);
				
				//删除session中无用的货物信息
				getSession().removeAttribute("cargoInfo");
			}
			else
			{
				this.setResultMsg("请输入货源信息");
				return ERROR;
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	
	public String cargoList()
	{
		try
		{
			GetCargosByUserIdEvt evt = new GetCargosByUserIdEvt();
			evt.setUserId(getLoginUser().getId());
		
			evt.setPageNo(pageNo);
			evt.setPageCount(PAGE_COUNT);
			
			cargoPage = cargoService.getCargosByUserId(evt);
		
		}
		catch (Exception e) 
		{
			e.fillInStackTrace();
		}
		return SUCCESS;
	}
	
	public String preEditCargo()
	{
		try
		{
			cargo = cargoService.getCargoInfoById(cargoId);
			
			if(cargo.getUserId() != getLoginUser().getId())
			{
				this.setResultMsg("您没有权利修改该货源信息");
				return ERROR;
			}
		}
		catch (Exception e) {
			return ERROR;
		}
		
		return SUCCESS;
	}

	public String editCargo()
	{
		try
		{
			long userId = getLoginUser().getId();
			
			CargoInfo cargoInfo = cargoService.getCargoInfoById(cargo.getId());
			
			// 判断当前用户是否有权限
			if(cargoInfo.getUserId() == userId)
			{
				cargoInfo.setType(cargo.getType());
				cargoInfo.setTitle(cargo.getTitle());
				cargoInfo.setPackageType(cargo.getPackageType());
				cargoInfo.setLength(cargo.getLength());
				cargoInfo.setWidth(cargo.getWidth());
				cargoInfo.setHeight(cargo.getHeight());
				cargoInfo.setNumber(cargo.getNumber());
				cargoInfo.setAmount(cargo.getAmount());
				cargoInfo.setVolume(cargo.getVolume());
				cargoInfo.setFreight(cargo.getFreight());
				cargoInfo.setCarRequired(cargo.getCarRequired());
				cargoInfo.setBidEndTime(cargo.getBidEndTime());
				cargoInfo.setOtherInfo(cargo.getOtherInfo());
				cargoInfo.setSender(cargo.getSender());
				cargoInfo.setSenderPhone(cargo.getSenderPhone());
				cargoInfo.setStartAddress(cargo.getStartAddress());
				cargoInfo.setStartCity(cargo.getStartCity());
				cargoInfo.setStartProvince(cargo.getStartProvince());
				cargoInfo.setStartTown(cargo.getStartTown());
				cargoInfo.setLoadStartTime(cargo.getLoadStartTime());
				cargoInfo.setLoadEndTime(cargo.getLoadEndTime());
				cargoInfo.setReceiver(cargo.getReceiver());
				cargoInfo.setReceiverPhone(cargo.getReceiverPhone());
				cargoInfo.setDestinationAddress(cargo.getDestinationAddress());
				cargoInfo.setDestinationCity(cargo.getDestinationCity());
				cargoInfo.setDestinationProvince(cargo.getDestinationProvince());
				cargoInfo.setDestinationTown(cargo.getDestinationTown());
				cargoInfo.setUnloadStartTime(cargo.getUnloadStartTime());
				cargoInfo.setUnloadEndTime(cargo.getUnloadEndTime());
				//待审核
				cargoInfo.setStatus(0);
				
				//将用户修改的货物信息先放到session中，在用户点击到下一步
				getSession().setAttribute("cargoInfo", cargoInfo);
				//cargoService.updateCargoInfo(cargo);
				
				//查询货物关联的发票信息
				invoice = invoiceService.getInvoiceById(cargoInfo.getInvoiceId());
				
				//获取用户的所有邮寄地址
				addressList= addressService.getAddressByUserId(userId);
				
			}
			else
			{
				this.setResultMsg("您没有权利修改该货源信息");
				return ERROR;
			}
		}
		catch (Exception e) 
		{
			this.setResultMsg("系统忙，请稍后再试");
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	public String editInvoice()
	{
		try {
			
			cargo = (CargoInfo)getSession().getAttribute("cargoInfo");
			//如果session中存在用户添加的货物信息，将其保存
			if(cargo != null)
			{
				if(hasInvoice.equalsIgnoreCase("yes"))
				{
					if(StringUtils.isEmpty(invoice.getTitle()))
					{
						this.setResultMsg("请输入发票抬头");
						return INPUT;
					}
					
					Address address = addressService.getAddressById(invoice.getAddressId());
					
					if(address == null)
					{
						this.setResultMsg("请选择邮寄地址");
						return INPUT;
					}
					
					//更新发票信息
					invoiceService.updateInvoice(invoice);

					cargo.setInvoiceId(invoice.getId());
				}
				else
				{
					//删除发票信息
					invoiceService.delInvoice(invoice.getId());
					
					//取消货物关联的发票
					cargo.setInvoiceId(0);
				}
				
				//更新货源信息
				cargoService.updateCargoInfo(cargo);
				
				//删除session中无用的货物信息
				getSession().removeAttribute("cargoInfo");
			}
			else
			{
				this.setResultMsg("数据参数错误，请重新操作");
				return ERROR;
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/**
	 * 为主动应标的车辆获取单个货物的部分信息
	 * 
	 * @return SUCCESS
	 */
	public String getCargoDetailForCar() {
		
//		this.goodsId = Integer.parseInt(getRequest().getParameter("goodsId"));
//		this.oneCargo = cargoService.getCargoInfoById(this.goodsId);
		
		this.cargoId = Long.parseLong(getRequest().getParameter("goodsId"));
		this.cargo = cargoService.getCargoInfoById(this.cargoId);
		
		return SUCCESS;
	}
	
	/**
	 * 获取单个货物的所有应标信息(应标人、应标车辆、应标价格)
	 * 
	 * @return SUCESS
	 */
	public String getAllBiddingCars() {
		
//		this.goodsId = Integer.parseInt(getRequest().getParameter("goodsId"));
//		this.cargoItem = cargoService.getCargoItemByGoodsId(this.goodsId);
		
		this.cargoId = Long.parseLong(getRequest().getParameter("goodsId"));
		this.cargoItem = cargoService.getCargoItemByGoodsId(this.cargoId);
		
		return SUCCESS;
	}
	
	public String queryCargo()
	{
		return SUCCESS;
	}
	
	public String delCargo()
	{
		return SUCCESS;
	}
	public CargoService getCargoService() {
		return cargoService;
	}

	public void setCargoService(CargoService cargoService) {
		this.cargoService = cargoService;
	}
	
	public CarPubInfoService getCarPubInfoService() {
		return carPubInfoService;
	}

	public void setCarPubInfoService(CarPubInfoService carPubInfoService) {
		this.carPubInfoService = carPubInfoService;
	}

	public CargoInfo getCargo() {
		return cargo;
	}

	public void setCargo(CargoInfo cargo) {
		this.cargo = cargo;
	}

	public List<CargoInfo> getCargoList() {
		return cargoList;
	}

	public void setCargoList(List<CargoInfo> cargoList) {
		this.cargoList = cargoList;
	}

	public long getCargoId() {
		return cargoId;
	}

	public void setCargoId(long cargoId) {
		this.cargoId = cargoId;
	}

	public Page getCargoPage() {
		return cargoPage;
	}

	public void setCargoPage(Page cargoPage) {
		this.cargoPage = cargoPage;
	}
	
	/**
	 * 获取当前时间
	 * 
	 * @return
	 */
	public Date getCurrentDate(){
		return new Date();
	}

	public CargoItem getCargoItem() {
		return cargoItem;
	}

	public void setCargoItem(CargoItem cargoItem) {
		this.cargoItem = cargoItem;
	}

	public AddressService getAddressService() {
		return addressService;
	}

	public void setAddressService(AddressService addressService) {
		this.addressService = addressService;
	}

	public List<Address> getAddressList() {
		return addressList;
	}

	public void setAddressList(List<Address> addressList) {
		this.addressList = addressList;
	}

	public InvoiceService getInvoiceService() {
		return invoiceService;
	}

	public void setInvoiceService(InvoiceService invoiceService) {
		this.invoiceService = invoiceService;
	}
	
	public BidInfoService getBidInfoService() {
		return bidInfoService;
	}

	public void setBidInfoService(BidInfoService bidInfoService) {
		this.bidInfoService = bidInfoService;
	}

	public Invoice getInvoice() {
		return invoice;
	}

	public void setInvoice(Invoice invoice) {
		this.invoice = invoice;
	}

	public String getHasInvoice() {
		return hasInvoice;
	}

	public void setHasInvoice(String hasInvoice) {
		this.hasInvoice = hasInvoice;
	}

	public List<BidCarInfoModel> getContactCarList() {
		return contactCarList;
	}

	public void setContactCarList(List<BidCarInfoModel> contactCarList) {
		this.contactCarList = contactCarList;
	}

	public Page getSimilarCargoPage() {
		return similarCargoPage;
	}

	public void setSimilarCargoPage(Page similarCargoPage) {
		this.similarCargoPage = similarCargoPage;
	}
	
}
